package com.junyuan.gsp.shiro;

import com.junyuan.gsp.bean.Role;
import com.junyuan.gsp.bean.User;
import com.junyuan.gsp.service.RoleService;
import com.junyuan.gsp.service.UserService;
import com.junyuan.gsp.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 普通登录验证
 *
 * @Author: maxwellens
 */
public class UserRealm extends AuthorizingRealm
{
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public boolean supports(AuthenticationToken token)
    {
        return true;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
    {
        if (token instanceof UsernamePasswordToken)
        {
            UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
            String username = usernamePasswordToken.getUsername();
            User user = userService.findUserByAccount(username);
            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        } else if (token instanceof JwtToken)
        {
            JwtToken jwtToken = (JwtToken) token;
            String username = JWTUtil.getUsername(jwtToken.getToken());
            User user = userService.findUserByAccount(username);
            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        } else
        {
            return null;
        }
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        //从凭证中获得用户名
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        //根据用户名查询用户对象
        User user = userService.findUserByAccount(username);
        //查询用户拥有的角色
        List<Role> roles = roleService.findRolesByIds(user.getRoles());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (Role role : roles)
        {
            info.addStringPermission(role.getName());
        }
        return info;
    }

}
